<?php
namespace Wx\Controller;
use Think\Controller;


class WholesaleController extends CommonController{

    public function _initialize(){
        parent::_initialize();

        //获取支付截止时间
        $pay_log_info = M("wholesale_pay_log")->where("state = 0")->field('id,addtime')->select();//获取所有支付记录

        foreach($pay_log_info as $pk => $pv){
            $deadline = strtotime(date('YmdHis',$pv['addtime'])." +1 hours")-time();
            $deadline = $deadline>0?$deadline:0;

            //支付状态更改
            if($deadline == 0){
                M("wholesale_pay_log")->where("id = {$pv['id']} AND state = 0")->save(['state'=>2]);//已失效
                $w_info = M("wholesale")->where("pay_log_id = {$pv['id']}")->field('id,g_id,num')->select();//订单id
                foreach ($w_info as $wk => $wv){
                    M("wholesale")->where("id = {$wv['id']}")->save(['state'=>1]);//订单已失效
                    M("shop_spellgroup")->where("id = {$wv['g_id']}")->setInc('num',$wv['num']);//退还库存
                }//end foreach
            }//end if
        }//end foreach

    }//end fun

    // 批发列表页
    public function index(){
        $shop_spellgroup = M('shop_spellgroup');    // 拼团商品表
        $member = M('member');                      // 用户表
        // 查询乡村拼团商品-排序大的在前，库存少的在前
        $page=1;
        if($_GET['page']>1)$page=$_GET['page'];//瀑布流调用
        $list = $shop_spellgroup->page($page.',10')->where('type=0 and state=1')->field('id,u_id,price,h_imgs,title,u_num,unit')->order('sorting desc,num asc,starttime asc')->select();

        foreach ($list as $k=>$v){
            // 发布人信息
            $list[$k]['f_realname'] = $member->where('id='.$v['u_id'])->getField('realname');
            $list[$k]['f_avatar'] = $member->where('id='.$v['u_id'])->getField('avatar');
            $list[$k]['f_village'] = M('member_farmers')->where('u_id='.$v['u_id'])->getField('village');
            //产品单位
            $list[$k]['p_unit'] = M('category')->where('id='.$v['unit'])->getField('title');
            // 产品第一张图片
            $img = explode(',',$v['h_imgs']);
            $list[$k]['p_img']=$img[0];//第一张图片作为封面图
            // 产品批发价
            $list[$k]['price_range'] = M('spellgroup_price_range')->where('sg_id='.$v['id'])->select();
        }
        $this->assign('list',$list);
        $this->display('list-pf');
    }//end function index

    // 搜索
    public function search(){
        // 搜索关键词
        $title = $_GET['title_keywords'];
        if($title!=''){
            $where ="`title` LIKE '%".$title."%' and ";
        }else{
            $where ="";
        }//end if
        $shop_spellgroup = M('shop_spellgroup');    // 拼团商品表
        $member = M('member');                      // 用户表
        // 查询乡村拼团商品-排序大的在前，库存少的在前
        $list = $shop_spellgroup->where($where.'type=0 and state=1')->field('id,u_id,price,h_imgs,title,u_num,unit')->order('sorting desc,num asc,starttime asc')->select();
        foreach ($list as $k=>$v){
            // 发布人信息
            $list[$k]['f_realname'] = $member->where('id='.$v['u_id'])->getField('realname');
            $list[$k]['f_avatar'] = $member->where('id='.$v['u_id'])->getField('avatar');
            $list[$k]['f_village'] = M('member_farmers')->where('u_id='.$v['u_id'])->getField('village');
            //产品单位
            $list[$k]['p_unit'] = M('category')->where('id='.$v['unit'])->getField('title');
            // 产品第一张图片
            $img = explode(',',$v['h_imgs']);
            $list[$k]['p_img']=$img[0];//第一张图片作为封面图
            // 产品批发价
            $list[$k]['price_range'] = M('spellgroup_price_range')->where('sg_id='.$v['id'])->select();
        }
//        dump($list);
        $this->assign('list',$list);
        $this->assign('title',$title);
        $this->display('list-search');
    }//end function search


    public function prodetail(){
        $id = intval(I('id'));
        $my_u_id = session('u_id');
        $member = M('member');  //用户表
        $member_farmers = M('member_farmers');  //农户表
        $area = M('area');
        $shop_spellgroup = M('shop_spellgroup');//拼团商品表
        // 商品信息
        $info = $shop_spellgroup->where('id='.$id)->field('id,u_id,price,h_imgs,num,title,content,u_num,unit,min_num')->find();
        // 商品批发价
        $info['price_range'] = M('spellgroup_price_range')->where('sg_id='.$info['id'])->select();
        // 商品图片
        $info['h_imgs'] = explode(',',$info['h_imgs']);
        //产品单位
        $info['p_unit'] = M('category')->where('id='.$info['unit'])->getField('title');
        // 发布人信息
        $u_info = $member->where('id='.$info['u_id'])->field('avatar,realname')->find();
        // 发布人村庄
        $farm = $member_farmers->where('u_id='.$info['u_id'])->find();
        $farm['a1'] = $area->where("id=".$farm['a_id_1'])->getField('name');
        $farm['a2'] = $area->where("id=".$farm['a_id_2'])->getField('name');
        $farm['a3'] = $area->where("id=".$farm['a_id_3'])->getField('name');
        $farm['a4'] = $area->where("id=".$farm['a_id_4'])->getField('name');
        $farm['a5'] = $area->where("id=".$farm['a_id_5'])->getField('name');

        $shopping_cart = M("wholesale")->where("u_id = {$my_u_id} AND g_id = {$info['id']} AND g_u_id = {$info['u_id']} AND state = 0")->field('num,price')->find();//当前商品 购物车信息

        $info['number_pf'] = isset($shopping_cart) ? $shopping_cart['num'] :$info['min_num'];//商品份数显示

        $info['wholesale'] = M("wholesale")->where("u_id = {$my_u_id} AND state = 0")->getField('count(id)');//购物车数量

        $this->assign('info',$info);
        $this->assign('u_info',$u_info);
        $this->assign('farm',$farm);
        $this->display('prodetail-pf');

    }//end function index

    //刷新购物车
    public function reloadcart(){
        $gid = $_POST['gid'];
        $number = $_POST['number'];
        $info = M("shop_spellgroup")->where("id={$gid}")->field("id,num,min_num")->find();//获取实时信息
        $price_range = M('spellgroup_price_range')->where('sg_id='.$info['id'])->select();// 商品批发价

        $number = $number < $info['min_num']?$info['min_num']:$number;

        if ($number > $info['num'] && $_POST['this_val'] == 1){
            $info['val'] = '库存不足,剩余'.$info['num']."份";
        }else{
            $info['number'] = $number;
        }//end if

        foreach($price_range as $v){
            if ($number >= $v['start'] && $number <= $v['end']){
                $info['price'] = $v['price'];//单价
            }//end if
        }//end foreach

        $this->ajaxReturn($info,"JSON");
    }//end fun

    //加入批发购物车
    public function addshopping(){
        $g_id = $_POST['gid'];//商品id
        $number = $_POST['number'];//商品份数
        $my_u_id = session('u_id');//当前用户id

        //相关信息
        $info = M('shop_spellgroup')->where('id='.$g_id)->field('id,u_id,price,num,min_num')->find();// 商品信息
        $number = $number < $info['min_num']?$info['min_num']:$number;

        $price_range = M('spellgroup_price_range')->where('sg_id='.$info['id'])->select();// 商品批发价

        foreach($price_range as $v){
            if ($number >= $v['start'] && $number <= $v['end']){
                $price_range = $v['price'];//单价
            }//end if
        }//end foreach

        $wholesale = M("wholesale")->where("u_id = {$my_u_id} AND g_id = {$info['id']} AND g_u_id = {$info['u_id']} AND state = 0")->find();//当前商品 购物车信息

        //库存检测
        if ($number > $info['num'] && $number >= $wholesale['num']) {
            $this->ajaxReturn(['state'=>1,'val'=>'库存不足,剩余'.$info['num'].'份'],'JSON');die;
        }//end if

        if ($number == $wholesale['num'] ){
            if ($_POST['op'] != 'payorder'){
                $this->ajaxReturn(['state'=>1],'JSON');die;
            }else{
                $this->ajaxReturn(['state'=>2,'wid'=>$wholesale['id']],'JSON');die;
            }//end if
        }//end if

        if(isset($wholesale)){
            //更新购物车参数
            $wholesale_save = array(
                'num' => $number,
                'price' => $price_range
            );

            $cart = M('wholesale')->where("id = {$wholesale['id']}")->save($wholesale_save);
        }else{
            //加入购物车的参数
            $wholesale_data = array(
                'u_id' => $my_u_id,
                'g_id' => $g_id,
                'g_u_id' => $info['u_id'],
                'num' => $number,
                'price'=> $price_range,
                'addtime' => time()
            );
            $cart = M('wholesale')->add($wholesale_data);

        }//end if

        if($_POST['op'] == 'shoppingorder'){
            if ($cart){
                $tonum = M("wholesale")->where("u_id = {$my_u_id} AND state = 0")->getField('count(id)');//购物车数量
                $this->ajaxReturn(['state'=>0,'val'=>'加入购物车成功','num'=>$tonum],'JSON');
            }else{
                $this->ajaxReturn(['state'=>1,'val'=>'加入购物车失败'],'JSON');
            }//end if
        }//end if

        if($_POST['op'] == 'payorder' && $cart){
            $pay_wid = $wholesale['id']?$wholesale['id']:$cart;
            $this->ajaxReturn(['state'=>2,'wid'=>$pay_wid],'JSON');die;
        }//end if


    }//end fun

    //购物车界面
    public function cart(){
        $my_u_id = session('u_id');

        $wholesale = M("wholesale")->where("u_id = {$my_u_id} AND state in(0,1)")->group('g_u_id')->field('g_u_id')->select();//发布人分类
        $num_top = count($wholesale);
        foreach($wholesale as $k => $v){
            $wholesale[$k]['commodity']=M("wholesale")->where("u_id = {$my_u_id} AND g_u_id = {$v['g_u_id']} AND state in(0,1)")->select();//获取购物车信息
            $wholesale[$k]['g_u_id'] = getMember($v['g_u_id'],'nickname,avatar');//获取发布人信息
            $wholesale[$k]['g_u_id']['farmers'] = M("member_farmers")->where("u_id = {$v['g_u_id']}")->getField('village');//获取发布人地址

            foreach($wholesale[$k]['commodity'] as $wk => $wv){

                $wholesale[$k]['commodity'][$wk]['store_info'] = M('shop_spellgroup')->where('id='.$wv['g_id'])->field('id,u_id,price,h_imgs,num,title,content,u_num,unit,min_num,state,endtime')->find();// 商品信息

                if ($wholesale[$k]['commodity'][$wk]['store_info']['state'] != 1 || time()>$wholesale[$k]['commodity'][$wk]['store_info']['endtime']){
                    M("wholesale")->where("id = {$wv['id']} AND state = 0")->save(['state'=>1]);//发布人分类
                }//end if 商品是否失效

                $wholesale[$k]['commodity'][$wk]['state_order'] = $wholesale[$k]['commodity'][$wk]['store_info']['num']-$wv['num'];//库存是否充足

                $wholesale[$k]['commodity'][$wk]['price_range'] = M('spellgroup_price_range')->where('sg_id='.$wv['g_id'])->select();// 商品批发价

            }//end foreach
        }//end foreach


        $this->assign('num_top',$num_top);
        $this->assign('wholesale',$wholesale);
        $this->display("cart");

    }//end fun shoppingcart()

    //批发购物车更改
    public function editshopping(){
        $op = $_POST['op']?$_POST['op']:'edit';
        $w_id = $_POST['wid'];//购物车id

        //获取总金额
        if ($op == 'price'){
            $price = array();
            foreach($w_id as $k){
                $cart= M('wholesale')->where("id = {$k}")->find();//购物车信息
                $price['all'] +=($cart['price']*$cart['num']);//总金额
            }//end foreach
            $price['all']=$price['all']?$price['all']:0;
            $price['charge'] = $price['all']*3/100;//手续费
            $this->ajaxReturn($price,"JSON");

        }//end if

        //删除订单
        if ($op == 'delete'){
//            $this->ajaxReturn(['state'=>0,'val'=>"删除成功！"],"JSON");
            if (is_array($w_id)){
                foreach($w_id as $k){
                    $cart = M('wholesale')->where("id = {$k}")->delete();//删除
                    if (empty($cart)){
                        $this->ajaxReturn(['state'=>1,'val'=>"删除失败！"],"JSON");
                    }//end if
                }//end foreach
            }else{
                $cart = M('wholesale')->where("id = {$w_id}")->delete();//删除
                if (empty($cart)){
                    $this->ajaxReturn(['state'=>1,'val'=>"删除失败！"],"JSON");
                }//end if
            }//end if

            $this->ajaxReturn(['state'=>0,'val'=>"删除成功！"],"JSON");

        }//end if

        //商品份数修改
        if($op == 'edit'){
            $g_id = $_POST['gid'];//商品id
            $number = $_POST['number']+$_POST['sym'];//商品份数

            $cart= M('wholesale')->where("id = {$w_id}")->find();//购物车信息
            $info = M('shop_spellgroup')->where('id='.$g_id)->field('id,u_id,price,num,min_num')->find();// 商品信息

            //商品份数检测
            if ($number == $cart['num'] || $number < $info['min_num']){
                $this->ajaxReturn(['state'=>1],'JSON');
                die;
            }//end if

            //库存检测
            if ($number > $info['num'] && $number > $cart['num']) {
                $this->ajaxReturn(['state'=>1,'val'=>'库存不足,剩余'.$info['num']."份"],'JSON');
                die;
            }//end if

            $price_range = M('spellgroup_price_range')->where('sg_id='.$info['id'])->select();// 商品批发价

            foreach($price_range as $v){
                if ($number >= $v['start'] && $number <= $v['end']){
                    $price_range = $v['price'];//单价
                }//end if
            }//end foreach


            //更新购物车参数
            $wholesale_save = array(
                'num' => $number,
                'price' => $price_range
            );
            $save_cart = M('wholesale')->where("id = {$w_id}")->save($wholesale_save);
            if ($save_cart){
                $tonum = M("wholesale")->where("id = {$w_id}")->field('num,price')->find();//购物车数量
                $tonum['state_order'] = $info['num']-$tonum['num'];//库存是否充足
                $this->ajaxReturn($tonum,'JSON');
            }//end if

        }//end if

    }//end fun

    //支付界面
    public function Payment(){
        $u_id = session("u_id");
        $address = M("address")->where("u_id = {$u_id}")->field("name,mobile,a_id_1,a_id_2,a_id_3,content,is_default")->order("is_default desc,add_time desc")->select();//获取默认地址

        $wid = $_GET['wid'];
        $wid = explode(',',$wid);//购物车id处理

        //获取订单信息
        $is_order = '';
        $order = array();
        foreach($wid as $k => $v){
            $order[$k] = M("wholesale")->where("id = {$v}")->find();//获取购物车信息
            $order[$k]['spellgroup'] = M("shop_spellgroup")->where("id = {$order[$k]['g_id']}")->find();//获取商品信息
            //检测库存
            if($_POST['op'] == 'order' || $_POST['op'] == 'pay'){
                if($order[$k]['num'] > $order[$k]['spellgroup']['num']){
                    $is_order = "false";
                }//end if
            }//end if
            $order[$k]['price_range'] = M('spellgroup_price_range')->where('sg_id='.$order[$k]['g_id']." AND price = {$order[$k]['price']}")->field("start,end")->find();// 商品批发区间
        }//end foreach

        //订单处理归类
        $wholesale = array();
        foreach($order as $k => $v){


            $wholesale[$v['g_u_id']]['wholesale'][] = $v;
            //发货人信息
            $wholesale[$v['g_u_id']]['member'] = getMember($v['g_u_id'],'avatar,nickname');//获取头像姓名
            $wholesale[$v['g_u_id']]['price_all'] += ($v['price']*$v['num']);
            $wholesale[$v['g_u_id']]['village'] = M("member_farmers")->where("u_id = {$v['g_u_id']}")->getField("village");//获取地址
        }//end foreach

        //生成订单
        if($_POST['op'] == 'order'){
//            $this->ajaxReturn($is_order,"JSON");
            if($is_order != "false"){
                $wholesale_arr = array(
                    'order_sn' => $_POST['order_sn'],
                    'content' => $_POST['content'],
                    'addtime' => time(),
                    "name"=>$_POST['name'],
                    "mobile"=>$_POST['mobile'],
                    "address"=>$_POST['address'],
                    "ordersn"=>$_POST['ordersn']
                );
                $add_wholesale = M("wholesale")->where("id = {$_POST['wid']}")->save($wholesale_arr);
                if ($add_wholesale){
                    $this->ajaxReturn(['state'=>0,'val'=>"success"],"JSON");
                }else{
                    $this->ajaxReturn(['state'=>1,'val'=>"error:".$_POST['wid']],"JSON");
                }//end if
            }else{
                $this->ajaxReturn(['state'=>1,'val'=>"库存不足"],"JSON");
            }//end if

        }//end if

        //生成pay_log
        if ($_POST['op']=="pay"){
            if($is_order != "false"){
                $pl_id = 0;
                foreach ($_POST['wid_pay'] as $wpk => $wpv){
                    $pay_id = M("wholesale")->where("id = {$wpv}")->getField("pay_log_id");//支付记录id
                    if ($pay_id != 0){
                        $pl_id = $pay_id;
                    }//end if
                }//end foreach

                //检测是否已生成，防止重复生成
                if ($pl_id != 0){

                    foreach ($_POST['wid_pay'] as $wpk => $wpv){
                        $pf_id = M("wholesale")->where("id = {$wpv}")->getField("pay_log_id");//支付记录id
                        if ($pf_id == 0) {
                            $g_info = M("wholesale")->where("id = {$wpv}")->field('g_id,num')->find();//获取商品id和已售库存
                            $shop_dec = M("shop_spellgroup")->where("id = {$g_info['g_id']}")->setDec('num',$g_info['num']);//减库存
                            if ($shop_dec){
                                M("wholesale")->where("id = {$wpv} AND state = 0")->save(['pay_log_id'=>$pl_id,"state"=>3]);//记录支付id
                            }else{
                                $this->ajaxReturn(['state'=>1,'val'=>"提交失败！"],"JSON");
                            }//end if
                        }//end if
                    }//end foreach
                    $this->ajaxReturn(['state'=>0,'pay_id'=>$pl_id],"JSON");
//                $this->ajaxReturn($pf_id,"JSON");
                }else{
                    $price_all = 0;
                    foreach ($wholesale as $wk => $wv){
                        foreach($wv['wholesale'] as $wsk => $wsv){
                            $price_all += ($wsv['price']*$wsv['num']);
                        }//end foreach
                    }//end foreach
                    $price_all += $price_all*3/100;//总价
                    $order_sn = 'PF'.date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);       //生成订单号
                    $pay_log = array(
                        'u_id' => session('u_id'),
                        'total_fee' => $price_all,
                        'order_sn' => $order_sn,
                        'addtime' => time()
                    );
                    $pay_log_id = M("wholesale_pay_log")->add($pay_log);
                    if ($pay_log_id){
                        foreach ($_POST['wid_pay'] as $wpk => $wpv){
                            $g_info = M("wholesale")->where("id = {$wpv}")->field('g_id,num')->find();//获取商品id和已售库存
                            $shop_dec = M("shop_spellgroup")->where("id = {$g_info['g_id']}")->setDec('num',$g_info['num']);//减库存
                            if ($shop_dec){
                                M("wholesale")->where("id = {$wpv} AND state = 0")->save(['pay_log_id'=>$pay_log_id,"state"=>3]);//记录支付id
                            }else{
                                $this->ajaxReturn(['state'=>1,'val'=>"提交失败！"],"JSON");
                            }//end if
                        }//end foreach
                        $this->ajaxReturn(['state'=>0,'pay_id'=>$pay_log_id],"JSON");
                    }else{
                        $this->ajaxReturn(['state'=>1,'val'=>"提交失败！"],"JSON");
                    }//end if
                }//end if

            }else{
                $this->ajaxReturn(['state'=>1,'val'=>"库存不足"],"JSON");
            }//end if

        }//end if
        $this->assign('wid',$wid);
        $this->assign('address',$address);
        $this->assign('wholesale',$wholesale);
        $this->display("confirmorder-pf");
//        dump($wholesale);
    }//end fun Payment()

//    //支付成功
//    public function paysuccess(){
//        $this->assign("price",$_GET['pay']);
//        $this->display("success");
//    }//end fun paysuccess()
}//end class